<template>
  <DynamicList
    ref="travelPlanListTable"
    v-bind="travelPlanListColumns"
    @load-data="onSearchData"
    @reset-data="onResetData"
  >
    <template #tableTop>
      <!--      <a-space class="flex-wrap" size="small">-->
      <!--        <a-button-->
      <!--          v-if="$auth('travel-plan-add')"-->
      <!--          type="primary"-->
      <!--          @click="router.push('/travelPlan/travelPlanDetail')"-->
      <!--        >-->
      <!--          <PlusOutlined />-->
      <!--          新增-->
      <!--        </a-button>-->
      <!--      </a-space>-->
    </template>
    <template #searchQuery>
      <div class="inline-flex items-center">
        <span class="pr-8px">发布时间：</span>
        <a-range-picker
          v-model:value="publishDate"
          :format="valueFormat"
          show-time
          @change="(date, dateString) => onRangeChange('publishDate', dateString)"
        />
      </div>
      <div class="inline-flex items-center">
        <span class="pr-8px">更新时间：</span>
        <a-range-picker
          v-model:value="updateDate"
          :format="valueFormat"
          show-time
          @change="(date, dateString) => onRangeChange('updateDate', dateString)"
        />
      </div>
      <div class="inline-flex items-center">
        <span class="pr-8px">审核时间：</span>
        <a-range-picker
          v-model:value="auditTDate"
          :format="valueFormat"
          show-time
          @change="(date, dateString) => onRangeChange('auditTDate', dateString)"
        />
      </div>
      <div class="inline-flex items-center">
        <span style="width: 100px">审核状态：</span>
        <a-checkbox-group v-model:value="queryData.auditStatus" style="width: 100%">
          <a-checkbox value="1">待审核</a-checkbox>
          <a-checkbox value="2">审核不通过</a-checkbox>
          <a-checkbox value="3">审核通过</a-checkbox>
        </a-checkbox-group>
      </div>
    </template>
  </DynamicList>
  <a-modal v-model:visible="auditVisible" title="查看结果" width="550px" :destroy-on-close="true">
    <a-form
      ref="passFormRef"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      :model="modelForm"
      :after-close="handleCloseCallback"
    >
      <a-form-item label="审核人">
        <a-input v-model:value="modelForm.auditor" disabled />
      </a-form-item>
      <a-form-item label="审核结果" name="status">
        <a-select v-model:value="modelForm.status" :options="auditOptions" disabled />
      </a-form-item>
      <a-form-item label="审核时间" name="auditTime">
        <a-date-picker
          v-model:value="modelForm.auditTime"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          disabled
        />
      </a-form-item>
      <a-form-item label="审核意见" name="remark">
        <a-textarea v-model:value="modelForm.remark" :rows="4" :maxlength="400" disabled />
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="flex justify-center">
        <a-button @click="auditVisible = false">关闭窗口</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="tsx">
  import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { Avatar, message, Modal, Tag } from 'ant-design-vue';
  import type { Dayjs } from 'dayjs';
  import { deleteTravelPlan, getTravelPlanAuditResults, travelPlanApi } from '@/api/travelPlan';
  import { formatToDateTime } from '@/utils/dateUtil';
  import DynamicList from '@/components/dynamicList/index.vue';
  import { RequestEnum } from '@/enums/httpEnum';
  import { publicPathUrl } from '@/utils/common';
  import useRequestList from '@/hooks/useRequestList';
  import { verifyAuth } from '@/core/permission';
  import { getFileHttpUrl } from '@/utils/urlUtils';
  import { useUserStore } from '@/store/modules/user';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import { publishMap, publishOptions, StatusEnum } from '@/enums/DisableEnum';
  import { auditOptions, AuditStatusEnum, auditStatusMap } from '@/enums/auditEnum';

  defineOptions({
    name: 'travelPlanList',
  });

  type RangeValue = [Dayjs, Dayjs];
  interface QueryDataParams {
    endPublishTime: string;
    startPublishTime: string;
    status: number | null;
    auditStatus: [] | null;
  }
  const publishDate = ref<RangeValue | string[]>();
  const updateDate = ref<RangeValue | string[]>();
  const auditTDate = ref<RangeValue | string[]>();
  const queryData = reactive<any>({
    endPublishTime: '',
    startPublishTime: '',
    endUpdateTime: '',
    startUpdateTime: '',
    endAuditTime: '',
    startAuditTime: '',
    // status: null,
    auditStatus: ['1'],
  });

  const userStore = useUserStore();
  const rustic = userStore.getRusticId();

  const valueFormat = 'YYYY-MM-DD HH:mm';
  const travelPlanListTable = ref<any>(null);
  const router = useRouter();
  const auditResult = reactive({
    auditVisible: false,
    modelForm: {
      auditor: '',
      status: '',
      auditTime: undefined as string | undefined,
      remark: '',
    },
  });
  const { auditVisible, modelForm } = toRefs(auditResult);

  const { list, page, setPage, setParams, loading } = useRequestList({
    apiKey: travelPlanApi.travelPlanList,
    type: RequestEnum.GET,
    initParam: {
      rusticId: rustic,
      auditStatus: queryData?.auditStatus?.join(),
    },
  });
  const travelPlanListColumns = ref({
    columns: [
      {
        title: '序号',
        width: 30,
        align: 'center',
        dataIndex: 'index',
        customRender: ({ record, text, index }) => index + 1,
      },
      {
        title: '封面',
        width: 60,
        align: 'center',
        dataIndex: 'cover',
        customRender: ({ text }) => {
          return text ? <a-image width="80px" src={getFileHttpUrl(text)} /> : '-';
        },
      },
      {
        title: '攻略名称',
        width: 100,
        align: 'center',
        dataIndex: 'name',
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      {
        title: '作者',
        width: 50,
        align: 'center',
        dataIndex: 'creator',
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      {
        title: '状态',
        width: 60,
        align: 'center',
        dataIndex: 'status',
        search: true,
        component: ComponentsTypeEnum.Select,
        componentProps: {
          options: publishOptions,
        },
        customRender: ({ record, text }) => {
          return publishMap[text] || '-';
        },
      },
      {
        title: '审核状态',
        width: 70,
        align: 'center',
        dataIndex: 'auditStatus',
        // search: true,
        // component: ComponentsTypeEnum.Select,
        // componentProps: {
        //   options: auditOptions,
        // },
        customRender: ({ record, text }) => {
          return auditStatusMap[text] || '-';
        },
      },
      {
        title: '审核人',
        width: 50,
        align: 'center',
        dataIndex: 'auditor',
        customRender: ({ record, text }) => {
          return record?.auditStatus == AuditStatusEnum.WAIT_AUDIT ? '暂无' : text;
        },
      },
      {
        title: '审核时间',
        width: 50,
        align: 'center',
        dataIndex: 'auditTime',
        customRender: ({ record, text }) => {
          if (record?.auditStatus == AuditStatusEnum.WAIT_AUDIT) return '暂无';
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '发布时间',
        width: 50,
        align: 'center',
        dataIndex: 'publishTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '更新时间',
        width: 50,
        align: 'center',
        dataIndex: 'updateTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '操作',
        width: 100,
        dataIndex: 'operation',
        align: 'center',
        fixed: 'right',
        actions: [
          {
            title: '详情',
            vIf: verifyAuth('travel-plan-detailPage'),
            onClick: (record) => {
              router.push(`/travelPlan/travelPlanDetail?id=${record.id}`);
            },
          },
          {
            title: '审核',
            vIf: (record) =>
              verifyAuth('travel-plan-audit') && record.auditStatus === AuditStatusEnum.WAIT_AUDIT,
            onClick: (record) => {
              router.push(`/travelPlan/travelPlanAudit?id=${record.id}`);
            },
          },
          {
            title: '审核结果',
            vIf: (record) =>
              verifyAuth('travel-plan-audit') && record.auditStatus !== AuditStatusEnum.WAIT_AUDIT,
            onClick: (record) => {
              handleOpenAuditPopup(record?.id);
            },
          },
          // {
          //   title: '删除',
          //   vIf: verifyAuth('travel-plan-delete'),
          //   onClick: (record) => {
          //     deleteConfirmTravelPlan(record);
          //   },
          // },
        ],
      },
    ],
    queryParamsSlots: queryData,
    pageParams: page,
    list,
    loading,
  });

  const deleteConfirmTravelPlan = async (record) => {
    Modal.confirm({
      title: '确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      centered: true,
      onOk: async () => {
        const res = await deleteTravelPlan({ id: record.id });
        if (res) {
          message.success(res?.msg);
          travelPlanListTable.value && travelPlanListTable.value.resetFields();
        }
      },
    });
  };

  const onSearchData = (queryParams) => {
    setParams({
      ...queryParams,
      rusticId: rustic,
      auditStatus: queryData?.auditStatus?.join(),
    });
  };

  const onResetData = (queryParams: Object) => {
    for (const queryParamsKey in queryData) {
      queryData[queryParamsKey] = null;
    }
    queryData.auditStatus = ['1'];
    publishDate.value = [queryData.startPublishTime, queryData.endPublishTime];
    updateDate.value = [queryData.startUpdateTime, queryData.endUpdateTime];
    auditTDate.value = [queryData.startAuditTime, queryData.endAuditTime];
    setParams({
      ...queryParams,
      ...queryData,
      rusticId: rustic,
      auditStatus: queryData?.auditStatus?.join(),
    });
  };
  const onRangeChange = (type: string, dateString: string[]) => {
    if (type === 'publishDate') {
      queryData.startPublishTime = dateString[0];
      queryData.endPublishTime = dateString[1];
    }
    if (type === 'updateDate') {
      queryData.startUpdateTime = dateString[0];
      queryData.endUpdateTime = dateString[1];
    }
    if (type === 'auditTDate') {
      queryData.startAuditTime = dateString[0];
      queryData.endAuditTime = dateString[1];
    }
  };

  const handleCloseCallback = () => {
    auditResult.auditVisible = false;
    auditResult.modelForm = {
      auditor: '',
      status: '',
      auditTime: undefined,
      remark: '',
    };
  };

  const handleOpenAuditPopup = async (id) => {
    auditResult.auditVisible = true;
    const res = await getTravelPlanAuditResults({ id });
    if (res) {
      const data = res?.data;
      auditResult.modelForm = {
        auditor: data?.auditor,
        status: data?.auditStatus,
        auditTime: formatToDateTime(data?.auditTime),
        remark: data?.auditRemark,
      };
    }
  };
</script>

<style></style>
